<template>
  <div class="page-order-refund">
    <div class="screening-conditions search-bar">
      <el-form
        :inline="true"
        :model="searchForm"
        @submit.prevent
        @keyup.enter="onGetDataList(page)"
      >
        <div class="input-row">
          <el-form-item :label="$t('order.refundId') + '：'">
            <el-input
              v-model="searchForm.refundSn"
              :placeholder="$t('order.refundId')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('prodList.shopName') + '：'">
            <el-input
              v-model="searchForm.shopName"
              :placeholder="$t('prodList.inputShopName')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.afterSalesStatus') + '：'">
            <el-select
              v-model="returnMoneySts"
              clearable
              :placeholder="$t('order.pleSelAfterSalesSta')"
              @change="orderRefundStatus"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('order.number') + '：'">
            <el-input
              v-model="searchForm.orderNumber"
              :placeholder="$t('order.number')"
              clearable
            />
          </el-form-item>

          <el-form-item :label="$t('order.orderType') + '：'">
            <el-select
              v-model="searchForm.orderType"
              clearable
              :placeholder="$t('order.selOrderType')"
            >
              <el-option
                v-for="item in orderType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            :label="$t('refundOrderDetail.refundType') + '：'"
          >
            <el-select
              v-model="searchForm.refundType"
              clearable
              :placeholder="
                $t('refundOrderDetail.selRefundType')
              "
            >
              <el-option
                v-for="item in refundType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            :label="$t('refundOrderDetail.applyWay') + '：'"
          >
            <el-select
              v-model="searchForm.applyType"
              clearable
              :placeholder="$t('refundOrderDetail.selApplyWay')"
            >
              <el-option
                v-for="item in applyType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('order.createTime') + '：'">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="—"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
            />
            <div
              style="margin-left: 20px;"
              class="default-btn"
              @click="onSetDateRange(1)"
            >
              {{
                $t("date.t")
              }}
            </div>
            <div
              class="default-btn"
              @click="onSetDateRange(2)"
            >
              {{
                $t("date.y")
              }}
            </div>
            <div
              class="default-btn"
              @click="onSetDateRange(3)"
            >
              {{
                $t("date.n")
              }}
            </div>
            <div
              class="default-btn"
              @click="onSetDateRange(4)"
            >
              {{
                $t("th")
              }}
            </div>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t("order.query") }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch()"
            >
              {{ $t("product.reset") }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container main">
      <div class="content">
        <!-- 导航 -->
        <div :class="['order-status-nav','clearfix',showHeadScroll?'status-nav-bottom':'']">
          <ul class="nav-list clearfix">
            <li
              :class="['nav-item-li', sts == 0 ? 'selected' : '']"
              data-sts="0"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                {{ $t("date.a") }}
              </span>
            </li>
            <li
              :class="['nav-item-li', sts == 1 ? 'selected' : '']"
              data-sts="1"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                {{ $t("refundOrderDetail.buyerApply") }}
              </span>
            </li>
            <li
              :class="['nav-item-li', sts == 2 ? 'selected' : '']"
              data-sts="2"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                {{ $t("refundOrderDetail.sellerAccepts") }}
              </span>
            </li>
            <li
              :class="['nav-item-li', sts == 3 ? 'selected' : '']"
              data-sts="3"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                {{ $t("refundOrderDetail.buyerDelivery") }}
              </span>
            </li>
            <li
              :class="['nav-item-li', sts == 4 ? 'selected' : '']"
              data-sts="4"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                {{ $t("refundOrderDetail.sellerReceivesGoods") }}
              </span>
            </li>
            <li
              :class="['nav-item-li', sts == 5 ? 'selected' : '']"
              data-sts="5"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                {{ $t("order.refundsuccessfully") }}
              </span>
            </li>
            <li
              :class="['nav-item-li', sts == -1 ? 'selected' : '']"
              data-sts="-1"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                {{ $t("order.refundClosed") }}
              </span>
            </li>
            <li
              :class="['nav-item-li', sts === 6 ? 'selected' : '']"
              data-sts="6"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                申请介入
              </span>
            </li>
            <li
              :class="['nav-item-li', sts === 7 ? 'selected' : '']"
              data-sts="7"
              @click="onSelectNav($event)"
            >
              <span class="li-txt">
                介入处理
              </span>
            </li>
          </ul>
          <ul class="nav-right" />
        </div>

        <!-- 列标题 -->
        <div :class="['tit', showHeadScroll ? sidebarFold?'fixed-top-fold':'fixed-top' : '']">
          <el-row style="width: 100%">
            <el-col :span="7">
              <span class="item product">{{ $t("order.product") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="transaction-price"
            >
              <span class="item">{{ $t("prodList.goodsPrice") }}/{{
                $t("order.quantity")
              }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{
                $t("refundOrderDetail.refundAmount")
              }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t("refundOrderDetail.comStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("refundOrderDetail.refundType") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("group.orderStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.afterSalesStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("remindPop.operation") }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="orderRefund in dataList"
          :key="orderRefund.refundId"
          class="prod"
        >
          <div class="prod-tit">
            <span>{{ $t("order.refundId") }}：{{ orderRefund.refundSn }}</span>
            <span>{{ $t("order.number") }}：{{ orderRefund.orderNumber }}</span>
            <span>{{ $t("order.applicationTime") }}：{{
              orderRefund.applyTime
            }}</span>
            <span>{{ $t("prodList.shopName") }}：{{ orderRefund.shopName }}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width: 100%">
              <el-col
                :span="10"
                style="height: 100%"
              >
                <div class="item prod-item">
                  <div
                    v-for="orderItem in orderRefund.orderItems"
                    :key="orderItem.orderItemId"
                    class="items name"
                  >
                    <div class="order-prod-item-info">
                      <!-- 商品信息 -->
                      <div class="info">
                        <div class="prod-image">
                          <prod-pic
                            height="60px"
                            width="60px"
                            :pic="orderItem.pic"
                          />
                        </div>
                        <div class="prod-name">
                          <div class="prod-con">
                            <div class="prod-name-txt">
                              {{ orderItem.prodName }}
                            </div>
                            <div
                              v-if="orderItem.skuName"
                              class="prod-name-sku"
                            >
                              {{ orderItem.skuName }}
                            </div>
                            <div
                              v-if="orderRefund.orderMold === 1"
                              class="order-status"
                            >
                              {{ $t("order.virtualOrder") }}
                            </div>
                            <div
                              v-if="
                                orderRefund.orderType === 1 ||
                                  orderRefund.orderType === 2
                              "
                              class="order-status"
                            >
                              {{
                                orderRefund.orderType === 1
                                  ? $t("order.groupPurchaseOrder")
                                  : orderRefund.orderType === 2
                                    ? $t("order.spikeOrder")
                                    : ""
                              }}
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- 赠品信息 -->
                      <div
                        v-if="orderItem.giveawayList"
                        class="order-prod-item-give-con"
                      >
                        <div
                          v-for="(giveawayItem, giveIndex) in orderItem.giveawayList"
                          :key="giveIndex"
                          class="giveaway-item"
                        >
                          <div class="giveaway-item-name">
                            【{{ $t('order.giveawayPord') }}】 {{ giveawayItem.prodName }}
                          </div>
                          <div class="giveaway-item-sku-count">
                            {{ giveawayItem.skuName || '' }} x{{ giveawayItem.prodCount }}
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="prod-price">
                      <span>{{ moneyFormat(orderItem.price) }}</span>
                      <span>{{ orderItem.prodCount + $t("order.piece") }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span class="totalprice">{{
                      moneyFormat(orderRefund.refundAmount) +
                        " + " +
                        orderRefund.refundScore +
                        " " +
                        $t("order.score")
                    }}</span>
                    <span>
                      {{ $t("order.total") }}
                      {{ orderRefund.goodsNum }}
                      {{ $t("order.piece") }}
                    </span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <span>{{
                      orderRefund.applyType === 1
                        ? $t("order.onlyRefund")
                        : $t("order.refundAndMoney")
                    }}</span>
                    <span class="totalprice">{{
                      orderRefund.isReceiver
                        ? $t("refundOrderDetail.goodsReceived")
                        : $t("refundOrderDetail.notRecevied")
                    }}</span>
                    <span class="totalprice">{{
                      orderRefund.buyerReason
                    }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span v-if="orderRefund.refundType === 1">{{
                      $t("refundOrderDetail.fullRefund")
                    }}</span>
                    <span v-if="orderRefund.refundType === 2">{{
                      $t("refundOrderDetail.sigGoosRefund")
                    }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span
                    v-if="orderRefund.status === 1"

                    type="danger"
                  >{{ $t("order.pendingPayment") }}</span>
                  <span
                    v-else-if="orderRefund.status === 2"

                    type="danger"
                  >{{ $t("order.toBeShipped") }}</span>
                  <span
                    v-else-if="orderRefund.status === 3"

                    type="danger"
                  >{{ $t("order.pendingReceipt") }}</span>
                  <span
                    v-else-if="orderRefund.status === 4"
                    type="danger"
                  >部分发货</span>
                  <span
                    v-else-if="orderRefund.status === 5"

                    type="danger"
                  >{{ $t("order.successfulTransaction") }}</span>
                  <span
                    v-else-if="orderRefund.status === 6"
                  >{{
                    $t("order.transactionFailed")
                  }}</span>
                  <span
                    v-else-if="orderRefund.status === 7"

                    type="danger"
                  >{{ $t("group.waitGroup") }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div
                  v-if="orderRefund.platformInterventionStatus && orderRefund.platformInterventionStatus!==-1"
                  class="item"
                >
                  <!-- 平台介入状态 -1.没有介入 1.用户申请介入 2.平台同意介入 3.平台拒绝介入 5.平台同意退款成功  7.平台介入处理中 -->
                  <span>{{
                    [
                      "",
                      '申请介入',
                      '',
                      $t('order.refundClosed'),
                      '',
                      $t('order.refundsuccessfully'),
                      '',
                      '介入处理'
                    ][orderRefund.platformInterventionStatus]
                  }}</span>
                </div>
                <div
                  v-else
                  class="item"
                >
                  <span
                    v-if="orderRefund.returnMoneySts === 1"

                    type="danger"
                  >{{ $t("refundOrderDetail.buyerApply") }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 2"

                    type="danger"
                  >{{ $t("refundOrderDetail.sellerAccepts") }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 3"

                    type="danger"
                  >{{ $t("refundOrderDetail.buyerDelivery") }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 4"

                    type="danger"
                  >{{ $t("refundOrderDetail.sellerReceivesGoods") }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 5"

                    type="danger"
                  >{{ $t("order.refundsuccessfully") }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 6"

                    type="danger"
                  >{{ $t("order.withdrawsApplication") }}</span>
                  <span
                    v-else

                    type="danger"
                  >{{
                    $t("order.refundClosed")
                  }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="operate">
                    <div
                      class="default-btn text-btn"
                      @click="onViewOrderHandle(orderRefund.orderNumber)"
                    >
                      {{ $t("order.viewOrder") }}
                    </div>
                    <div
                      class="default-btn text-btn"
                      @click="toImbox(orderRefund)"
                    >
                      {{ $t("order.contactBuyer") }}
                    </div>
                    <div
                      class="default-btn text-btn"
                      @click="
                        onRefundHandle(orderRefund.refundId, orderRefund.shopId)
                      "
                    >
                      {{ $t("order.processingRefunds") }}
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div
          v-if="!dataList.length"
          class="empty"
        >
          {{ $t("order.noData") }}
        </div>
      </div>
    </div>
    <el-pagination
      v-if="dataList.length"
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import moment from 'moment'

// eslint-disable-next-line no-undef
defineOptions({
  name: 'order/order-refund/index'
})

const options = [{
  value: 1,
  label: $t('refundOrderDetail.buyerApply')
}, {
  value: 2,
  label: $t('refundOrderDetail.sellerAccepts')
}, {
  value: 3,
  label: $t('refundOrderDetail.buyerDelivery')
}, {
  value: 4,
  label: $t('refundOrderDetail.sellerReceivesGoods')
}, {
  value: 5,
  label: $t('order.refundsuccessfully')
}, {
  value: -1,
  label: $t('order.refundClosed')
}, {
  value: 6,
  label: '申请介入'
}, {
  value: 7,
  label: '介入处理'
}]
const orderType = [{
  value: 0,
  label: $t('order.normalOrder')
}, {
  value: 1,
  label: $t('order.groupPurchaseOrder')
}, {
  value: 2,
  label: $t('order.spikeOrder')
}]
const refundType = [{
  value: 1,
  label: $t('refundOrderDetail.fullRefund')
}, {
  value: 2,
  label: $t('refundOrderDetail.sigGoosRefund')
}]
const applyType = [{
  value: 1,
  label: $t('order.onlyRefund')
}, {
  value: 2,
  label: $t('order.refundAndMoney')
}]
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const commonStore = useCommonStore()
const sidebarFold = computed({
  get () { return commonStore.sidebarFold },
  set (val) { commonStore.updateSidebarFold(val) }
})

onActivated(() => {
  onGetDataList(page)
})

let resizeProportion = 1
const searchForm = ref({})
onMounted(() => {
  // 携带参数查询
  searchForm.value = useRoute().query
  onGetDataList(page)

  // 监听页面滚动
  window.addEventListener('scroll', onScrollToTop)

  resizeProportion = window.outerHeight / window.innerHeight
  window.addEventListener('resize', function () {
    resizeProportion = window.outerHeight / window.innerHeight
  })
})

/**
 * 页面滚动事件
 */
const showHeadScroll = ref(false)
const onScrollToTop = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > (400 * resizeProportion)
}

/**
 * 获取数据列表
 */
let tempSearchForm = null // 保存上次点击查询的请求条件
const returnMoneySts = ref(null)
const sts = ref(0)
const dateRange = ref([])
const dataList = ref([])
const onGetDataList = (pageParam, newData = false) => {
  const params = searchForm.value
  let paramReturnMoneySts = returnMoneySts.value || null
  let handleInterventionStatus = null
  if (returnMoneySts.value === 6 || returnMoneySts.value === 7) {
    paramReturnMoneySts = null
    handleInterventionStatus = returnMoneySts.value === 6 ? 1 : 2
  }
  if (newData || !tempSearchForm) {
    tempSearchForm = {
      current: pageParam.currentPage,
      size: pageParam.pageSize,
      orderNumber: params ? (params.orderNumber ? params.orderNumber : null) : null,
      shopName: params ? (params.shopName ? params.shopName : null) : null,
      returnMoneySts: paramReturnMoneySts,
      handleInterventionStatus,
      refundSn: params ? (params.refundSn ? params.refundSn : null) : null,
      orderType: params ? ((params.orderType || params.orderType === 0) ? params.orderType : null) : null,
      applyType: params ? (params.applyType ? params.applyType : null) : null,
      refundType: params ? (params.refundType ? params.refundType : null) : null,
      startTime: dateRange.value ? (dateRange.value[0] ? dateRange.value[0] : null) : null, // 开始时间
      endTime: dateRange.value ? (dateRange.value[1] ? dateRange.value[1] : null) : null // 结束时间
    }
  } else {
    tempSearchForm.current = page.currentPage
    tempSearchForm.size = page.pageSize
    tempSearchForm.returnMoneySts = paramReturnMoneySts
    tempSearchForm.handleInterventionStatus = handleInterventionStatus
  }
  http({
    url: http.adornUrl('/platform/orderRefund/page'),
    method: 'get',
    params: http.adornParams(Object.assign(tempSearchForm))
  }).then(({ data }) => {
    data.records.forEach(order => {
      if (order.refundType === 1 && order.orderItems.length > 1) {
        let goodsNum = 0
        for (let i = 0; i < order.orderItems.length; i++) {
          const element = order.orderItems[i]
          goodsNum += element.prodCount
        }
        order.goodsNum = goodsNum
      }
    })
    dataList.value = data.records
    page.total = data.total
    sts.value = returnMoneySts.value || 0
  })
}
const orderRefundStatus = (val) => {
  returnMoneySts.value = val
}
// 每页数
const sizeChangeHandle = (val) => {
  page.pageSize = val
  page.currentPage = 1
  onGetDataList(page)
}
// 当前页
const currentChangeHandle = (val) => {
  page.currentPage = val
  onGetDataList(page)
}

// 前往消息盒子
const toImbox = (order) => {
  if (order.userWriteOff) {
    ElMessage({
      message: $t('order.userlogoutTips'),
      type: 'error'
    })
    return
  }
  if (isAuth('message:message:view')) {
    const path = router.resolve({
      path: '/message-box/index',
      query: {
        userId: order.userId,
        orderNumber: order.orderNumber
      }
    })
    window.open(path.href, 'view_window', 'noopener,noreferrer')
  } else {
    ElMessage.info($t('home.authTip'))
  }
}

/**
 * 导航选择状态
 */
const onSelectNav = (e) => {
  const stsVal = e.currentTarget.dataset.sts
  sts.value = parseInt(stsVal)
  returnMoneySts.value = sts.value === 0 ? null : parseInt(stsVal)
  page.currentPage = 1
  onGetDataList(page)
}
/**
 * 查看订单
 */
const router = useRouter()
const onViewOrderHandle = (id) => {
  router.push({
    path: '/self/order-info/index',
    query: {
      orderNumber: id
    }
  })
}
/**
 * 处理退款
 */
const onRefundHandle = (id, shopId) => {
  router.push({
    path: '/self/refund-order-info/index',
    query: {
      refundId: id,
      shopId
    }
  })
}
/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const onSetDateRange = (val) => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -7
    endDay = -1
  } else if (val === 4) {
    startDay = -30
    endDay = -1
  } else {
    return
  }
  // 开始时间
  const startTime = moment().add(startDay, 'days').startOf('days').format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  dateRange.value = [startTime, endTime]
}
// 清空按钮
const onResetSearch = () => {
  searchForm.value = {}
  dateRange.value = []
  returnMoneySts.value = null
}
const onSearch = (newData = false) => {
  page.currentPage = 1
  page.pageSize = 10
  onGetDataList(page, newData)
}

</script>
<style lang="scss" scoped>
@use './index.scss';
</style>
